/**
 * @file search page
 * @author sunbai
 */

/* global Page, swan */
import {
    componentDictionary,
} from './dictionary';
import pinyin from 'js-pinyin';

/* eslint-disable babel/new-cap */
Page({
/* eslint-enable babel/new-cap */
    data: {
        value: '',
        focus: true,
        likeFocus: false,
        component: [],
        history: [],
        hot: [{subName: '支付', id: 'payment'},
            {subName: '拨打电话', id: 'make-phone-call'},
            {subName: '语音识别', id: 'get-voice-manager'},
            {subName: '车型识别', id: 'car-classify'},
            {subName: '动物识别', id: 'animal-classify'},
            {subName: '植物识别', id: 'plant-classify'},
            {subName: '设置页面标题', id: 'set-navigation-bar-title'}],
        hasResult: false,
        hasHistory: true,
        showEmptyResult: false,
        blur: true,
        subPackageName: '',
        loading: true,
    },
    onShow() {
        this.getHistoryStorage();
    },
    searchFocus(e) {
        this.setData({
            focus: true
        });
        if (e.detail.value !== '') {
            this.setData({
                likeFocus: true
            });
        }
    },
    searchInput(e) {
        const value = e.detail.value;
        clearTimeout(this.timeId);
        this.setData({
            value,
            likeFocus: true,
            component: [],
            hasResult: false,
            showEmptyResult: false
        });
        if (!value) {
            this.setData({
                likeFocus: false
            });
            this.resetResult();
            return false;
        }

        if (value.length === 1 && /[a-zA-Z]/.test(value)) {
            this.resetResult();
            return false;
        }
        this.timeId = setTimeout(() => {
            this.getSearchResult(value);
        }, 1000);
    },
    searchConfirm(e) {
        const value = this.getData('value').replace(/\s/gi, '');
        if (value) {
            this.setData({
                showEmptyResult: true,
                hasHistory: true
            });
            this.getSearchResult(value);
            this.setHistoryStorage(value);
        }

        this.setData({
            likeFocus: false
        });
        this.setData({
            focus: false
        });
    },
    searchBlur(e) {
        if (e.detail.value === '') {
            this.setData({
                likeFocus: false,
                focus: false
            });
        }
        else if (this.getData('showEmptyResult')) {
            this.setData({
                focus: false
            });
        }

        let showEmptyResult = this.getData('showEmptyResult');
        if (showEmptyResult) {
            this.setData({
                likeFocus: false
            });
        }

    },
    searchClear() {
        this.setData({
            value: '',
            likeFocus: false,
            component: [],
            hasResult: false,
            showEmptyResult: false
        });
    },
    historyClear() {
        swan.showModal({
            content: '确定清空相关历史？',
            confirmText: '确定',
            cancelText: '取消',
            success: res => {
                if (res.cancel) {
                }
                else if (res.confirm) {
                    this.setData({
                        history: [],
                        hasHistory: false
                    });
                    swan.clearStorageSync('history');
                }

            }
        });
    },
    getSearchResult(value) {
        let pingyinValue = pinyin.getFullChars(value);
        let newValue = value.toLowerCase();
        swan.request({
            url: 'https://host.com/api/search?name=' + value,
            header: {
                'content-type': 'application/json'
            },
            method: 'GET',
            success: res => {
                console.log('request success', res);
                if (res.data)
                {
                    const component = res.data;
                    const hasResult = component.length;
                    this.setData({component, hasResult});
                } else {
                    const component = [];
                    const hasResult = component.length;
                    this.setData({component, hasResult});
                }

            },
            fail: err => {
                const component = [];
                const hasResult = component.length;
                this.setData({component, hasResult});
                console.log('request fail', err);
            },
            complete: () => {
                this.setData('loading', false);
                console.log('request complete');
            }
        });
    },
    compareDictionary(value) {},
    resetResult() {
        this.setData({
            component: [],
            hasResult: false
        });
    },
    openPage(e) {
        swan.navigateTo({
            url: "/show?id="+e.currentTarget.dataset.say
        });
    },
    setHistoryStorage(value) {
        const history = this.getData('history');
        const index = history.findIndex(item => item === value);
        if (index > -1) {
            history.splice(index, 1);
        }

        history.unshift(value);
        swan.setStorageSync('history', history);
        this.setData('history', history);
    },
    getHistoryStorage() {
        let history = swan.getStorageSync('history');
        if (history.length === 0) {
            this.setData('hasHistory', false);
        }
        else {
            this.setData('hasHistory', true);
        }
        if (!Array.isArray(history)) {
            history = [];
        }

        this.setData('history', history);
    },
    openSearch(e) {
        const word = e.currentTarget.dataset.word;
        this.setData({
            value: word
        });
        this.getSearchResult(word);
        this.searchConfirm(word);
    }
});
